import HTTP from './HTTP.js';
import Util from './Util.js';

const desktop = parent.window.desktop;

HTTP.ajax({
    url: '/application/AppStore/allApps',
    contentType: 'application/json',
    success: (data) => {
        function hasApp(projectName, callback) {
            // TODO 使用系统暴露的属性需要请求权限
            callback && callback(desktop.hasApp(projectName));
        }

        function addApp(projectName, p) {
            hasApp(projectName, (flag) => {
                if (!flag) {
                    HTTP.ajax({
                        url: `/app/${JSON.parse(window.localStorage.user).name}/addApp/${projectName}`,
                        success: (data) => {
                            p.innerHTML = '已拥有应用';
                            p.className = 'add-app disable';
                            let app = null;
                            try {
                                app = JSON.parse(data.response);
                            } catch { }
                            if (app) {
                                desktop.addApp(app);
                            }
                        }
                    });
                }
            })
        }

        const appStoreContainer = document.getElementById('appStoreContainer');

        function showTip(mask, flag) {

            const p = document.createElement('p');

            p.innerHTML = flag ? '获取应用' : '已拥有应用';
            p.className = flag ? 'add-app' : 'add-app disable';

            mask.innerHTML = '';

            const timer = Util.timer();

            let opacityMask = 0;
            timer.set(() => {
                mask.style.backgroundColor = `rgba(96, 96, 96, ${opacityMask})`;
                opacityMask += 0.1;
                if (opacityMask > 0.5) {
                    timer.clear();
                }
            }, 16);

            mask.appendChild(p);
            return p;
        }

        const apps = JSON.parse(data.response)
        showApps(apps, 'office');

        const appStoreOfficeBtn = document.getElementById('appStoreOfficeBtn');
        const appStoreEntertainmentBtn = document.getElementById('appStoreEntertainmentBtn');
        const appStoreAllBtn = document.getElementById('appStoreAllBtn');
        const appStoreSystem = document.getElementById('appStoreSystem');

        function clearClassName() {
            const nav = appStoreOfficeBtn.parentElement;
            for (let i = 0; i < nav.children.length; i++) {
                nav.children[i].className = '';
            }
        }

        appStoreOfficeBtn.addEventListener('click', function () {
            clearClassName();
            this.className = 'current';
            showApps(apps, 'office');
        });

        appStoreEntertainmentBtn.addEventListener('click', function () {
            clearClassName();
            this.className = 'current';
            showApps(apps, 'entertainment');
        });

        appStoreAllBtn.addEventListener('click', function () {
            clearClassName();
            this.className = 'current';
            showApps(apps, 'all');
        });

        appStoreSystem.addEventListener('click', function () {
            clearClassName();
            this.className = 'current';
            showApps(apps, 'system');
        })

        function showApps(apps, type) {
            appStoreContainer.innerHTML = '';
            let counter = 0;
            for (const id in apps) {
                if (apps[id].type === type || type === 'all') {
                    // 不显示商店本身
                    if (apps[id].name === 'AppStore') continue;
                    // 不显示系统应用
                    // if (apps[id].type === 'system') continue;
                    const li = document.createElement('li');

                    li.innerHTML = `
                        <img class="cover" src="${apps[id].cover}" alt="${apps[id].icon}">
                        <h2 class="title">${apps[id].name}</h2>
                        <p class="desc" title="${apps[id].description}">${apps[id].description}</p>
                        <div class="mask" id=appStore_${id}></div>
                    `;
                    appStoreContainer.appendChild(li);
                    counter++;

                    const mask = document.getElementById(`appStore_${id}`);
                    mask.addEventListener('mouseenter', function (event) {

                        if (this.children.length === 0) {

                            const projectName = apps[id].projectName;
                            hasApp(projectName, (flag) => {
                                if (!flag) {
                                    // 没有添加该应用
                                    const p = showTip(this, true);

                                    p.addEventListener('click', () => {
                                        addApp(projectName, p);
                                    });

                                } else {
                                    // 添加了该应用
                                    showTip(this, false);
                                }
                            });
                        }
                    });

                    mask.addEventListener('mouseleave', function () {
                        const timer = Util.timer();
                        this.innerHTML = '';

                        let opacityMask = 0.5;
                        timer.set(() => {
                            this.style.backgroundColor = `rgba(96, 96, 96, ${opacityMask})`;
                            opacityMask -= 0.1;
                            if (opacityMask < 0) {
                                timer.clear();
                            }
                        }, 16);
                    })

                }
            }
            // 不满四个的一行新增空白盒子
            for (let i = 0; i < counter % 4; i++) {
                const li = document.createElement('li');
                li.className = 'empty'
                appStoreContainer.appendChild(li);
            }
        }
    },
    error: (err) => {
        console.log(err);
    }
});
